layui.define(['jquery', 'layer'], function (exports) {
    "use strict";
    var $ = layui.$;
    var layer = layui.layer;

    // 存储打开的弹出层引用
    var openLayers = {};

    var utils = {
        bsm_popup: function (title, url, level, width, height) {
            var scale = 0.7;
            if (level === 1) { scale = 0.7; }
            if (level === 2) { scale = 0.6; }

            if (width && height) {
                layer.open({
                    type: 2,
                    title: title,
                    area: [width + 'px', height + 'px'],
                    content: url
                });
            } else {
                layer.open({
                    type: 2,
                    title: title,
                    area: [(window.screen.width * scale) + 'px', (window.screen.height * scale) + 'px'],
                    content: url
                });
            }
        },

        // 增强的打开弹窗函数
        openPopupWithCallback: function (title, url, options, closeCallback) {
            var settings = $.extend({
                width: '800px',
                height: '600px',
                autoResize: true,
                minWidth: 600,
                minHeight: 400,
                maxWidth: window.innerWidth * 0.8,
                maxHeight: window.innerHeight * 0.8
            }, options);

            var layerIndex = layer.open({
                type: 2,
                title: title,
                area: [settings.width, settings.height],
                content: url,
                resize: true,
                cancel: function (index, layero) {
                    // 获取iframe窗口对象
                    var iframeWin = layero.find('iframe')[0].contentWindow;

                    // 检查弹出层是否有未保存的数据
                    if (iframeWin && typeof iframeWin.hasUnsavedChanges === 'function') {
                        if (iframeWin.hasUnsavedChanges()) {
                            layer.confirm('有未保存的更改，是否保存？', {
                                icon: 3,
                                title: '保存确认',
                                btn: ['保存', '不保存', '取消']
                            }, function (i) {
                                // 保存按钮
                                if (iframeWin && typeof iframeWin.saveData === 'function') {
                                    iframeWin.saveData(function (success) {
                                        if (success) {
                                            layer.close(i);
                                            layer.close(index);
                                            if (typeof closeCallback === 'function') {
                                                closeCallback(true);
                                            }
                                        }
                                    });
                                }
                            }, function (i) {
                                // 不保存按钮
                                layer.close(i);
                                layer.close(index);
                                if (typeof closeCallback === 'function') {
                                    closeCallback(false);
                                }
                            });

                            return false; // 阻止默认关闭行为
                        }
                    }
                },
                success: function (layero, index) {
                    // 为每个弹窗创建独立的消息处理器
                    var messageHandler = function (event) {
                        if (event.data && event.data.type === 'resizePopup') {
                            utils.handlePopupResize(index, event.data, settings);
                        }
                    };

                    // 存储处理器引用，便于后续移除
                    openLayers[index] = {
                        url: url,
                        closeCallback: closeCallback,
                        messageHandler: messageHandler
                    };

                    window.addEventListener('message', messageHandler);
                },
                end: function (index) {
                    // 清理工作
                    if (openLayers[index] && openLayers[index].messageHandler) {
                        window.removeEventListener('message', openLayers[index].messageHandler);
                        delete openLayers[index];
                    }

                    if (typeof settings.onClose === 'function') {
                        settings.onClose();
                    }
                }
            });

            return layerIndex;
        },

        // 处理弹出层调整
        handlePopupResize: function (index, data, settings) {
            var targetWidth = data.width || settings.width;
            var targetHeight = data.height || settings.height;

            // 确保是数字类型
            targetWidth = parseInt(targetWidth);
            targetHeight = parseInt(targetHeight);

            // 限制尺寸范围
            targetWidth = Math.max(targetWidth, settings.minWidth);
            targetHeight = Math.max(targetHeight, settings.minHeight);
            targetWidth = Math.min(targetWidth, settings.maxWidth);
            targetHeight = Math.min(targetHeight, settings.maxHeight);

            // 调整弹出层尺寸
            layer.style(index, {
                width: targetWidth + 'px',
                height: targetHeight + 'px'
            });

            // 重新定位居中
            layer.iframeAuto(index);
        },

        // 计算内容尺寸并通知父窗口（供子页面调用）
        notifyParentResize: function (customOptions) {
            var options = $.extend({
                minWidth: 600,
                minHeight: 400,
                extraWidth: 40,
                extraHeight: 100
            }, customOptions);

            // 计算内容实际需要的尺寸
            var contentWidth = document.body.scrollWidth;
            var contentHeight = document.body.scrollHeight;

            // 加上边框、标题栏等额外空间
            var targetWidth = Math.max(contentWidth + options.extraWidth, options.minWidth);
            var targetHeight = Math.max(contentHeight + options.extraHeight, options.minHeight);

            // 发送消息给父窗口
            if (window.parent !== window) {
                window.parent.postMessage({
                    type: 'resizePopup',
                    width: targetWidth,
                    height: targetHeight,
                    source: window.name || 'unknown'
                }, '*');
            }
        },

        // 为表格页面设置的自动调整功能
        setupTableAutoResize: function (tableId, customOptions) {
            var table = layui.table;
            var $ = layui.$;

            var options = $.extend({
                tableExtraWidth: 40,
                tableExtraHeight: 80,
                minWidth: 600,
                minHeight: 400
            }, customOptions);

            function calculateTableSize() {
                var $table = $('#' + tableId).next('.layui-table-view');
                if ($table.length === 0) return null;

                var tableWidth = $table.outerWidth();
                var tableHeight = $table.outerHeight();

                // 计算需要的总尺寸
                var neededWidth = Math.max(tableWidth + options.tableExtraWidth, options.minWidth);
                var neededHeight = Math.max(tableHeight + options.tableExtraHeight, options.minHeight);

                return {
                    width: neededWidth,
                    height: neededHeight
                };
            }

            // 表格渲染完成后调整
            table.on('done(' + tableId + ')', function () {
                setTimeout(function () {
                    var size = calculateTableSize();
                    if (size) {
                        window.parent.postMessage({
                            type: 'resizePopup',
                            width: size.width,
                            height: size.height,
                            source: 'tablePage_' + tableId
                        }, '*');
                    }
                }, 300);
            });

            // 初始调整
            setTimeout(function () {
                var size = calculateTableSize();
                if (size) {
                    window.parent.postMessage({
                        type: 'resizePopup',
                        width: size.width,
                        height: size.height,
                        source: 'tablePage_' + tableId
                    }, '*');
                }
            }, 500);
        },

        // 简化的打开弹窗函数（兼容旧代码）
        openPopup: function (title, url, options) {
            return this.openPopupWithCallback(title, url, options);
        },

        getSessionId: function () {
            try {
                const sessionData = localStorage.getItem('session');
                if (!sessionData) {
                    return null;
                }

                const session = JSON.parse(sessionData);
                return session.session_id || null;
            } catch (error) {
                console.error('解析 session 数据失败:', error);
                return null;
            }
        },

        // 登出事件 - 增强版本
        logOut: function () {
            layer.confirm('确定要退出登录吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);

                const loading = layer.load(1);

                // 直接使用 http.logout()，它已经包含了所有清理逻辑
                http.logout()
                    .then(() => {
                        layer.msg('已安全退出', {
                            icon: 1,
                            time: 1000
                        });
                    })
                    .catch(err => {
                        // 即使失败，http.logout 也已经清理了本地存储
                        console.log('登出过程完成:', err);
                    })
                    .finally(() => {
                        layer.close(loading);

                        // 统一跳转逻辑
                        if (window.history?.replaceState) {
                            window.history.replaceState(null, null, '/');
                        }
                        setTimeout(() => {
                            window.location.replace('/');
                        }, 1000);
                    });
            });
        },

        GetMe: function () {
            // 从localStorage获取用户信息
            const userData = localStorage.getItem('user');
            if (userData) {
                try {
                    const user = JSON.parse(userData);
                    return user;
                }
                catch (error) {
                    console.error('解析用户数据失败:', error);
                    return null;
                }
            } else {
                return null;
            }
        },
    }

        exports('bsm_utils', utils);
    });